package com.macro.mall.portal.component;

import com.macro.mall.portal.common.MallConst;
import com.macro.mall.portal.service.UmsCommentService;
import com.macro.mall.portal.service.UmsTopicService;
import com.macro.mall.security.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class TopicTask {
    private Logger LOGGER = LoggerFactory.getLogger(TopicTask.class);
    @Autowired
    private UmsTopicService umsTopicService;
    @Autowired
    private RedisService redisService;

    /**
     * cron表达式：Seconds Minutes Hours DayofMonth Month DayofWeek [Year]
     * 每10分钟扫描一次，把评论的浏览数回写到数据库
     */
    @Scheduled(cron = "0 0/5 * ? * ?")
    private void topicBrowseCountToDB(){
        Map<Object, Object> topicIds = redisService.hGetAll(MallConst.RKEY_COMMENT_BROWSECOUNT+"BROWSECOUNT");
        for (Object topicId : topicIds.keySet()) {
            Long count = Long.parseLong(topicIds.get(topicId).toString());
            if (count > 0) {
                //回写到数据库
                umsTopicService.updateBrowsecount(Integer.parseInt(topicId.toString()),Integer.parseInt(count.toString()));
                redisService.hIncr(MallConst.RKEY_COMMENT_BROWSECOUNT+"BROWSECOUNT",topicId.toString(),-count);
            }
        }

    }
}
